import compressor from "js-image-compressor"
export default function (options = {}) {
  // 压缩参数
  let { compressOptions = {}, uploadOptions = {} } = options
  this.compressOptions = {
    ...compressOptions,
    loose: compressOptions.loose || true,
    redressOrientation: compressOptions.redressOrientation || false,
    maxHeight: compressOptions.maxHeight || 2000,
    maxWidth: compressOptions.maxWidth || 2000,
    quality: compressOptions.quality || 0.8
  }
  // 上传参数
  this.uploadOptions = uploadOptions;

  /**
   * @Author: LAB
   * @description: 压缩图片
   * @param {file} file 待压缩图片
   * @param {*} funCompressOptions 压缩参数 参见js-image-compressor
   * @return {promise} Promise 压缩成功图片
   */
  this.compressImg = function (file, funCompressOptions = {}) {
    return new Promise((resolve) => {
      new compressor({
        ...this.compressOptions,
        ...funCompressOptions,
        file,
        success: function (pic) {
          resolve(pic)
        }
      })
    })
  }

  /**
   * @Author: LAB
   * @description: 上传图片
   * @param {*} file
   * @param {*} upLoadObject
   * @return {*}
   */
  this.uploadFile = function (file, upLoadObject = {}) {
    let { maxSize = 3000, uploadFunction = null } = this.uploadOptions
    const defaltSize = maxSize * 1000
    return new Promise((resolve, reject) => {
      if (typeof uploadFunction != "function") {
        reject(`请在初始化时指定上传方法options.uploadOptions.uploadFunction`)
        return
      }
      if (file.size > defaltSize) {
        reject(`图片文件大小最大为${maxSize / 1000}M`)
        return
      }
      let formData = new FormData()
      let final = upLoadObject || this.uploadOptions.upLoadObject || {}
      for (const key in final) {
        if (Object.hasOwnProperty.call(final, key)) {
          let element = final[key];
          formData.append(key, element)
        }
      }
      formData.append("file", file)
      try {
        this.uploadOptions.uploadFunction(formData).then(result => {
          resolve(result)
        }).catch(err => {
          reject(err || "上传图片失败")
        })
      } catch (error) {
        reject("上传函数有误:" + error)
      }
    })
  }
}

// // 导出压缩上传图片对象
// export default new fileToolsBase({
//   uploadOptions: {
//     uploadFunction: function (formData) {
//       let config = {
//         headers: { 'Content-Type': 'multipart/form-data' }
//       };
//       return new Promise((resolve, reject) => {
//         axios.post('/api/blade-resource/oss/endpoint/upload', formData, config).then(res => {
//           if (res.data.code == "200") {
//             resolve(res.data.data)
//           } else {
//             reject(res.data.msg || "上传图片失败")
//           }
//         }).catch(err => {
//           reject(err || "上传图片失败")
//         })
//       })

//     }
//   }
// })